package org.fickler

import org.apache.spark.sql.{SaveMode, SparkSession}
import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.sql.functions._

/**
 * @author Fickler
 * @date 2024/1/7 18:32
 */
object UkWeather {

  def main(args: Array[String]): Unit = {

    val conf = new SparkConf().setMaster("local[*]").setAppName("UK")
    val sc = new SparkContext(conf)

    val spark = SparkSession.builder.appName("AccidentImpactByWeather").getOrCreate()

    val inputPath = "src/main/java/org/datas/dft-road-casualty-statistics-accident-1979-2020.csv"
    val df = spark.read.option("header", "true").csv(inputPath)

    // 根据weather_conditions列进行分组计数
    val accidentImpactByWeather = df.groupBy("weather_conditions")
      .agg(count("*").alias("accident_count"))
      .orderBy(desc("accident_count"))

    accidentImpactByWeather.show()

    val outputPath = "src/main/java/org/UkResult/UkWeather"
    accidentImpactByWeather
      .coalesce(1)  // 将结果合并为一个分区
      .write
      .mode("overwrite")
      .option("header", "true")
      .csv(outputPath)

    val mysqlUrl = "jdbc:mysql://localhost:3306/ukaccident"
    val mysqlProperties = new java.util.Properties()
    mysqlProperties.setProperty("user", "root")
    mysqlProperties.setProperty("password", "011216")
    mysqlProperties.setProperty("driver", "com.mysql.jdbc.Driver")

    accidentImpactByWeather.write
      .mode(SaveMode.Overwrite)
      .jdbc(mysqlUrl, "UkWeather", mysqlProperties)

    spark.stop()
  }

}
